<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 18-1-4
 * Time: 下午5:41
 */

namespace app\model;


use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class UserList extends CommentModel
{
    protected $table="f_user_list";

    /**
     * 根据订单设置佣金
     * @param $order_no
     */
    function set_rebate($order_no)
    {
        $OrderList = new OrderList();
        $FConfig = new FConfigList();

        $user_rebate = $FConfig->where(["name" => "USER_REBATE"])->value("value");
        if (empty($user_rebate)) {
            $user_rebate = [];
        } else {
            $user_rebate = json_decode($user_rebate, true);
        }
        $agent_rebate = $FConfig->where(["name" => "AGENT_REBATE"])->value("value");

        try {
            $order_info = $OrderList->where(["order_no" => $order_no])->find();
            $user_id = $order_info["user_id"];
            $agent_id = $order_info["agent_id"];
            $basic_price = $order_info["basic_price"];
            if($agent_id>0)
            {
                $this->setAgentRebate($agent_id,$user_id,0, $basic_price*$agent_rebate, $order_no);
            }else{
                if ($user_id > 0) {
                    $r_id_list = $this->user_pid($user_id, count($user_rebate), []);
                    foreach ($r_id_list as $key => $r_id) {
                        $rebate = !empty($user_rebate[$key]) && floatval($user_rebate[$key]) > 0 ? floatval($user_rebate[$key]) : 0;

                        $this->setRebate($r_id,$user_id, $basic_price,$key,$basic_price * $rebate, $order_no);
                    }
                }
            }


        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
        }
    }

    /**
     * 查询上一级代理ID
     * @param $user_id
     * @param $count
     * @param $list
     * @return array
     */
    function user_pid($user_id, $count, $list)
    {
        if ($count < 1) return $list;
        $r_id = $this->where(["id" => $user_id])->value("r_id");
        if ($r_id > 0) {
            $list[] = $r_id;
            $list = $this->user_pid($r_id, $count - 1, $list);
        }
        return $list;
    }

    /**
     * 添加用户佣金
     * @param $user_id
     * @param $from_user_id
     * @param $amount
     * @param $level
     * @param $money
     * @param $order_no
     */
    function setRebate($user_id,$from_user_id,$amount,$level, $money, $order_no)
    {
        Db::startTrans();
        try {
            $WalletLog = new WalletLog();
            $CommissionReport = new CommissionReport();
            $info = ["user_id" => $user_id,"from_user_id"=>$from_user_id, "order_no" => $order_no,"type"=>0, "money" => $money,"level"=>$level, "info" => "", "ctime" => NOW_TIME];
            $id = $WalletLog->insertGetId($info);
            if(empty($id)) exception("更新失败");
            $query = $this->where(["id" => $user_id])->setInc("rebate", $money);
            if(empty($query)) exception("更新失败");
            $query = $this->where(["id" => $user_id])->setInc("total_rebate", $money);
            if(empty($query)) exception("更新失败");
            $count = $CommissionReport->where(["user_id" => $user_id,"from_user_id"=>$from_user_id])->count();
            if($count <1)
            {
                $info = ["user_id" => $user_id,"from_user_id"=>$from_user_id, "amount" => $amount, "money" => $money,"level"=>$level];
                $query = $CommissionReport->insert($info);
                if(empty($query)) exception("插入统计表失败");
            }else{

                $query = $this->where(["user_id" => $user_id,"from_user_id"=>$from_user_id])->setInc("amount", $amount);
                if(empty($query)) exception("更新失败");
                $query = $this->where(["user_id" => $user_id,"from_user_id"=>$from_user_id])->setInc("money", $amount);
                if(empty($query)) exception("更新失败");
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }

    }

    /**
     * 添加代理佣金
     * @param $agent_id
     * @param $from_user_id
     * @param $level
     * @param $money
     * @param $order_no
     * @param string $info
     * @return bool
     */
    function setAgentRebate($agent_id,$from_user_id,$level, $money, $order_no,$info="")
    {
        Db::startTrans();
        try {
            $WalletLog = new WalletLog();
            $AgentList = new AgentList();
            $info = ["agent_id" => $agent_id,"from_user_id"=>$from_user_id, "order_no" => $order_no,"type"=>1, "money" => $money,"level"=>$level, "info" => $info, "ctime" => NOW_TIME];
            $query = $WalletLog->insert($info);
            if(empty($query)) exception("更新失败");

            $query = $AgentList->where(["id" => $agent_id])->inc("rebate", $money)->inc("total_rebate", $money)->update();
            if(empty($query)) exception("更新失败");

            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

        }
        return false;
    }

    /**
     * 提现
     * @param $user_id
     * @param $openId
     * @param $money
     * @param string $ip
     * @return bool|string
     */
    function transfers($user_id,$openId,$money,$ip="127.0.0.1")
    {
        Db::startTrans();
        try {
            $TransfersList = new TransfersList();
            $query = $this->where(["id"=>$user_id,"rebate"=>[">=",$money]])->setDec("rebate",$money);
            if(empty($query)) exception("更新失败");
            $trade_no = get_order_no("T");
            $query = $TransfersList->insert(["trade_no"=>$trade_no,"user_id"=>$user_id,"open_id"=>$openId,"money"=>$money,"ctime"=>NOW_TIME,"ip"=>$ip]);
            if(empty($query)) exception("更新失败");
            // 提交事务
            Db::commit();
            return $trade_no;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return false;
    }
}